package com.ruicar.afs.cloud.afscase.job.approve.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkProcessScheduleInfo;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkProcessScheduleInfoService;
import com.ruicar.afs.cloud.afscase.common.utils.Const;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.processor.enums.WorkflowType;
import com.ruicar.afs.cloud.afscase.processor.service.ApproveWorkflowService;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.WorkFlowResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>Description:</p>
 * 审批定时任务服务类：<br/>
 *      1、自动撤销案件
 *      6、无操作监测
 * @author maxueyu
 * */
@Service
@Slf4j
@AllArgsConstructor
public class ApproveJobService {

    private final ApproveWorkflowService approveWorkflowService;
    private final WorkProcessScheduleInfoService workProcessScheduleInfoService;


    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public void processAutoCancelFlow(CaseBaseInfo caseBaseInfo){
        try{
            List<String> normalWorkflowTypes = new ArrayList<>();
            normalWorkflowTypes.add(WorkflowType.NORMAL_NEW.getAfsFlowKey());
            normalWorkflowTypes.add(WorkflowType.NORMAL_OLD.getAfsFlowKey());
            List<WorkProcessScheduleInfo> workProcessScheduleList = workProcessScheduleInfoService.list(
                    Wrappers.<WorkProcessScheduleInfo>lambdaQuery()
                            .in(WorkProcessScheduleInfo::getAfsFlowKey,normalWorkflowTypes)
                            .eq(WorkProcessScheduleInfo::getApplyNo,caseBaseInfo.getApplyNo())
                            .orderByDesc(WorkProcessScheduleInfo::getCreateTime));
            if(CollectionUtil.isNotEmpty(workProcessScheduleList)){
                WorkFlowResponse response = approveWorkflowService.cancelFlow(String.valueOf(workProcessScheduleList.get(0).getId()),
                        "【审批超时，系统自动撤销】");
                if (Const.WORKFLOW_RESPONSE_SUCCESS != response.getSuccess()) {
                    log.error("定时任务【自动撤销案件】执行失败，原因：{}",response.getMessage());
                    throw new RuntimeException(response.getMessage());
                }else{
                    log.info("申请编号{}已完成自动撤销",caseBaseInfo.getApplyNo());
                }
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException(e.getMessage());
        }
    }
}
